import 'package:drag_and_drop_lists/drag_and_drop_list_interface.dart';
import 'package:drag_and_drop_lists/drag_and_drop_lists.dart';

import 'package:flutter/material.dart';
import 'package:hixing_app/extensions/iterable_ext.dart';
import 'package:hixing_app/views/test_view/drag_model.dart';

class TestDragPage extends StatefulWidget {
  const TestDragPage({Key? key}) : super(key: key);

  @override
  State createState() => _DragHandleExample();
}

class _DragHandleExample extends State<TestDragPage> {
  late List<DragAndDropList> _contents;
  final List<DragModel> dragList = [
    DragModel(childList: [
      "child  1.1",
      "child  1.2",
      "child  1.3",
    ], title: "Header 1", value: 0),
    DragModel(childList: [
      "child  2.1",
      "child  2.2",
      "child  2.3",
    ], title: "Header 2", value: 1),
    DragModel(childList: [
      "child  3.1",
      "child  3.2",
      "child  3.3",
    ], title: "Header 3", value: 2),
    DragModel(childList: [
      "child  4.1",
      "child  4.2",
      "child  4.3",
    ], title: "Header 4", value: 3),
  ];

  /// type 0 :头部添加，1，尾部添加
  void addGroup(type) {
    DragAndDropList item = getAddWidget(canDrag: false);
    if (type == 0) {
      _contents.insert(0, item);
    } else {
      _contents.add(item);
    }
  }

  void removeNull() {
    Future.delayed(Duration(milliseconds: 200), () {
      DragAndDropList? item;
      _contents.forEachIndex((index) {
        if (index != 0 &&
            index != _contents.length - 1 &&
            _contents[index].children.isEmpty) {
          item = _contents[index];
          print("删除当前的空数组");
          setState(() {});
        }
      });
      if (item != null) {
        _contents.remove(item);
      }
    });
  }

  @override
  void initState() {
    super.initState();

    _contents = List.generate(dragList.length, (index) {
      return DragAndDropList(
          canDrag: true,
          header: Row(
            children: [
              Padding(
                padding: const EdgeInsets.only(left: 8, bottom: 4),
                child: Text(
                  dragList[index].title,
                  style: const TextStyle(
                      fontWeight: FontWeight.bold, fontSize: 16),
                ),
              ),
            ],
          ),
          children: List.generate(
            dragList[index].childList.length,
            (childIndex) => DragAndDropItem(
              child: Row(
                children: [
                  Padding(
                    padding:
                        const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
                    child: Text(
                      dragList[index].childList[childIndex],
                    ),
                  ),
                ],
              ),
            ),
          ).toList());
    });
    addGroup(0);
    addGroup(1);
  }

  @override
  Widget build(BuildContext context) {
    var backgroundColor = const Color.fromARGB(255, 243, 242, 248);

    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        title: const Text('Drag Handle'),
        actions: [ElevatedButton(onPressed: () {}, child: Text("查看当前数据"))],
      ),
      body: DragAndDropLists(
        children: _contents,

        onItemReorder: _onItemReorder,
        onListReorder: _onListReorder,

        itemOnAccept: (oldItem, newItem) {
          removeNull();
        },
        listPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        itemDivider: Divider(
          thickness: 2,
          height: 2,
          color: backgroundColor,
        ),
        itemDecorationWhileDragging: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 3,
              offset: const Offset(0, 0), // changes position of shadow
            ),
          ],
        ),
        listInnerDecoration: BoxDecoration(
          color: Theme.of(context).canvasColor,
          borderRadius: const BorderRadius.all(Radius.circular(8.0)),
        ),
        lastItemTargetHeight: 8,
        addLastItemTargetHeightToTop: true,
        lastListTargetSize: 40,

        // listGhost: const SizedBox(
        //   height: 50,
        //   width: 100,
        //   child: Center(
        //     child: Icon(Icons.add),
        //   ),
        // ),
        listDragHandle: const DragHandle(
          verticalAlignment: DragHandleVerticalAlignment.top,
          child: Padding(
            padding: EdgeInsets.only(right: 10),
            child: Icon(
              Icons.menu,
              color: Colors.black26,
            ),
          ),
        ),
        itemDragHandle: const DragHandle(
          child: Padding(
            padding: EdgeInsets.only(right: 10),
            child: Icon(
              Icons.menu,
              color: Colors.blueGrey,
            ),
          ),
        ),
      ),
    );
  }

  _onItemReorder(
      int oldItemIndex, int oldListIndex, int newItemIndex, int newListIndex) {
    /// 在这里把数据列表的排序同步跟组件列表的排序一致
    /// 注意，头尾塞入了空的数组用来处理新增的逻辑，所以index都要补偿回没塞入前的idnex
    if (newListIndex == 0) {
      _contents[0] = getAddWidget(canDrag: true);
    } else if (newListIndex == _contents.length - 1) {
      _contents[_contents.length - 1] = getAddWidget(canDrag: true);
    }
    setState(() {
      var movedItem = _contents[oldListIndex].children.removeAt(oldItemIndex);
      _contents[newListIndex].children.insert(newItemIndex, movedItem);

      /// 判断oldindex是单个数据当成数组头的，把老的数组删除
      if (newListIndex == 0) {
        addGroup(0);
        removeNull();
      } else if (newListIndex == _contents.length - 1) {
        addGroup(1);
        removeNull();
      }
    });
  }

  _onListReorder(int oldListIndex, int newListIndex) {
    /// 在这里把数据列表的排序同步跟组件列表的排序一致,
    /// 注意，头尾塞入了空的数组用来处理新增的逻辑，所以index都要补偿回没塞入前的idnex
    setState(() {
      var movedList = _contents.removeAt(oldListIndex);
      _contents.insert(newListIndex, movedList);
    });
  }

  getAddWidget({canDrag = false}) {
    return DragAndDropList(
      canDrag: canDrag,
      contentsWhenEmpty: Icon(Icons.add),
      header: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 8, bottom: 4),
            child: Text(
              "添加元素",
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
            ),
          ),
        ],
      ),
      children: [],
    );
  }
}
